<script setup lang="ts">
import { useList } from '@/composables/useList';
import { useSkuInfo } from '@/stores/skuInfo';
import { useProductInfo } from '@/stores/productInfo';
import type { OnPage } from '@/composables/useList';
import { useCacheScrollTop } from '@/composables/useCacheScrollTop';
import { Tag, showConfirmDialog, showSuccessToast } from 'vant';
import { h, ref } from 'vue';
import { useRouter } from 'vue-router';
import { mygoodList, updIfonsale, delGoods } from '@/common/api/hbMarket';

const skuInfo = useSkuInfo();
const productInfo = useProductInfo();
const router = useRouter();

// 缓存页面滚动位置
useCacheScrollTop('main', 'myPosts');

// 审核状态 0，未通过审核，1：通过审核
const status = ref(1);

const server: OnPage = async (listConfig) => {
  const res = await mygoodList({ ...listConfig, status: status.value });
  const { list } = res.result;
  // console.log('OnPage: ', list);
  return list;
};

const { list, loading, finished, error, refreshing, onLoad, onRefresh, onRefreshCurrent } = useList(server, true);

// 商品状态标签
interface StatusTagProps {
  status: number; //状态0：待上架，1：已上架
}
const StatusTag = (props: StatusTagProps) => {
  switch (props.status) {
    case 0:
      return h(Tag, { type: 'primary' }, () => '待上架');
    case 1:
      return h(Tag, { type: 'success' }, () => '上架');
    default:
      return h(Tag, { type: 'danger' }, () => '失效');
  }
};

// 商品上下架
const handleSell = async (item: any) => {
  try {
    const isSell = item.ifonsale === 0;
    await showConfirmDialog({ title: '提示', message: `确认${isSell ? '上架' : '下架'} ${item.title} ？` });
    await updIfonsale({ pid: item.pid, ifonsale: isSell ? 1 : 0 });
    showSuccessToast('操作成功');
    onRefreshCurrent();
  } catch {
    /** empty */
  }
};

// 商品删除
const handleDelte = async (item: any) => {
  console.log(item);
  try {
    await showConfirmDialog({ title: '提示', message: `确认删除 ${item.title} ？` });
    await delGoods({ pid: item.pid });
    showSuccessToast('操作成功');
    onRefreshCurrent();
  } catch {
    /** empty */
  }
};

// 商品编辑
const handleEdit = (item: any) => {
  // 清除缓存
  skuInfo.clearSkuInfo();
  productInfo.clearProductForm();
  router.push(`/hbMarket/productForm?pid=${item.pid}`);
};
</script>
<template>
  <div class="myPosts">
    <div class="h-[44px]">
      <div class="fixed w-full z-[1000]">
        <van-tabs v-model:active="status" @change="onRefresh(true)">
          <van-tab title="通过审核" :name="1"></van-tab>
          <van-tab title="待审核" :name="0"></van-tab>
          <van-tab title="审核未通过" :name="3"></van-tab>
        </van-tabs>
      </div>
    </div>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        v-model:error="error"
        :finished="finished"
        finished-text="没有更多了"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <div class="p-3">
          <van-card
            class="rounded-xl !pt-3 !bg-white"
            v-for="item in list"
            :key="item.pid"
            :price= "`${(item.price || 0).toFixed(1)} 积分`"
            :origin-price="`${(item.oriprice || 0).toFixed(1)}积分`"
            currency=""
            :desc="item.memo"
            :title="item.title"
            :thumb="item.images ? item.images.split(',')[0] : ''"
            @click="handleEdit(item)"
          >
            <template #tags>
              <StatusTag class="mt-1" :status="item.ifonsale" />
            </template>
            <template #footer>
              <van-button size="small" plain type="danger" @click.stop="handleDelte(item)">删除</van-button>
              <van-button size="small" plain type="primary" @click.stop="handleSell(item)">
                {{ item.ifonsale === 0 ? '上架' : '下架' }}
              </van-button>
            </template>
          </van-card>
          <!-- 底部安全区 -->
          <div class="van-safe-area-bottom"></div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<style lang="less" scoped>
.myPosts {
  min-height: 100%;
  background: #fafafa;
}
</style>
